
package jtrimet.android.widget;

import java.util.*;

import jtrimet.*;
import jtrimet.android.Util;
import android.content.Context;
import android.view.*;
import android.widget.*;

public class TrimetView extends LinearLayout
{
	private Button submit;
	private EditText busStopField;
	private TrimetClient client;
	private ArrivalListView arrivalsView;
	
	public TrimetView(final Context context)
	{
		super(context);
		
		this.setOrientation(LinearLayout.VERTICAL);
		
		client = new TrimetClient();
		
		submit = new Button(context);
		submit.setOnClickListener(new OnClickListener()
		{

			public void onClick(View v)
			{
				
				if (busStopField.getText().length() > 0)
				{
					submit.setEnabled(false);
					if (arrivalsView != null)
					{
						TrimetView.this.removeView(arrivalsView);
						arrivalsView = null;
					}
					
					
					Runnable getLocations = new Runnable()
					{
						
						public void run()
						{
							
							final Collection<Location> locations;

							Runnable updateUI = null;
							
							try
							{
								locations = client.getArrivalInformation(busStopField.getText().toString());
								updateUI = new Runnable()
								{
									public void run()
									{
											for (Location loc : locations)
											{
													arrivalsView = new ArrivalListView(context, loc.getArrivals());
													TrimetView.this.addView(arrivalsView);
											}
											submit.setEnabled(true);
									}
								};
							}
							catch (Exception ex)
							{
								ex.printStackTrace(); // todo : fix this
								updateUI = new Runnable()
								{
									public void run()
									{
										submit.setEnabled(true);
									}
								};
							}
							
							runOnUiThread(updateUI);
							
						}
					};
					
					Util.startThread(getLocations);
					
				}
			}
			
		});
		
		submit.setText("Submit");
		
		busStopField = new EditText(context)
		{
			public boolean onKeyUp(int keyCode, KeyEvent event)
			{
				if ( (keyCode == KeyEvent.KEYCODE_ENTER) || (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) )
				{
					submit.requestFocus();
					submit.performClick();
					return true;
				}
				else
				{
					return super.onKeyUp(keyCode, event);
				}
			}
		};
		
		busStopField.setSingleLine(true);
		busStopField.setWidth(100);
		
		/*
		busStopField.setOnKeyListener(new View.OnKeyListener()
		{

			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_ENTER)
				{
					submit.c
				}
			}
			
		}); */
		
		TextView busStopLabel = new TextView(context);
		busStopLabel.setText("Bus stop");
		
		this.addView(busStopLabel);
		this.addView(busStopField);
		this.addView(submit);
	}


	protected void runOnUiThread(Runnable r)
	{
		this.post(r);
	}
}
